package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.controller.form.SaveRoleAccountForm;
import com.woniuxy.controller.info.Result;
import com.woniuxy.model.AccountRule;
import com.woniuxy.dao.AccountRuleDao;
import com.woniuxy.model.Rule;
import com.woniuxy.service.AccountRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.RuleService;
import com.woniuxy.util.exception.accountException.RuleNotFindException;
import com.woniuxy.util.exception.code.RuleExceptionCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Kevin Martin
 * @since 2022-03-16
 */
@Service
public class AccountRuleServiceImpl extends ServiceImpl<AccountRuleDao, AccountRule> implements AccountRuleService {
    @Autowired
    private RuleService ruleService;

    @Override
    public Result saveRoleByAccountId(SaveRoleAccountForm saveRoleAccountForm) {
        if(saveRoleAccountForm.getRoleIds().size()!=0){
            QueryWrapper<Rule> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("rule_id",saveRoleAccountForm.getRoleIds());
            List<Rule> list = ruleService.list(queryWrapper);
            if(list.size()!=saveRoleAccountForm.getRoleIds().size()){
                throw new RuleNotFindException(RuleExceptionCode.Rule_NOTFIND_ERROR);
            }
        }
        QueryWrapper<AccountRule> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("account_id",saveRoleAccountForm.getAccountId());
        boolean remove = remove(queryWrapper1);
        if(saveRoleAccountForm.getRoleIds().size()==0){
            return Result.getInstance(String.class).setData("授权成功");
        }
        List<AccountRule> accountRules = new ArrayList<>();
        for (Integer roleId : saveRoleAccountForm.getRoleIds()) {
            AccountRule accountRule = new AccountRule();
            accountRule.setAccountId(saveRoleAccountForm.getAccountId());
            accountRule.setRuleId(roleId);
            accountRules.add(accountRule);
        }
        boolean b = saveBatch(accountRules);
        return b?Result.getInstance(String.class).setData("授权成功"):Result.getInstance(String.class).setData("授权失败");
    }
}
